import React,{MouseEvent,useEffect,useState,useRef} from "react";
import { Dialog,SwipeAction,Toast } from 'antd-mobile'
import PubSub from "pubsub-js";

import ShoppingItem from "./ShoppingItem";
import { Ivegetable } from "../../Frontpage/SpecialOffer";
import {Imessage} from "../../Frontpage/SpecialOffer/DiscountItem";

import style from './index.module.css'
import axios from "axios";
const {shoppingMain,delivery,click,switchDelivery} = style


export default function ShoppingMain(){

    const clickLi = useRef<HTMLLIElement>(null)
    const [vegetable,setVegetable] = useState<Ivegetable[]>()

    const [flag,setFlag] = useState(false)

    //标记周几配送
    const [deliveryTime,setDeliveryTime] = useState(true)

    useEffect(() => {
        const now = new Date()
        if(now.getDay() === 2 || now.getDay() === 3 || now.getDay() === 4 ||  now.getDay() === 4){
            setDeliveryTime(false)
        }
        axios.get('/api/shoppingCart')
            .then(res=>{
                setVegetable(res.data.shoppingCart as Ivegetable[])
            })
    }, [])



    function selected(event:MouseEvent){
        const li = event.currentTarget as HTMLLIElement

        if(li.id === click){
            li.id = ''
            setFlag(false)
        }else{
            li.id = click
            setFlag(true)
        }
    }

    function NotAllSelected(){
        clickLi.current && (clickLi.current.id = '')
        
    }

    function change(event:MouseEvent){
        const li = event.currentTarget as HTMLLIElement
        li.id !== switchDelivery && setDeliveryTime(!deliveryTime)
    }

    return (
        <div className={shoppingMain}>
            <ul className={delivery}>
                <li onClick={selected} ref={clickLi}/>
                <li onClick={change} id={ deliveryTime ? switchDelivery : ''}>周二配送</li>
                <li onClick={change} id={ deliveryTime ? '' : switchDelivery}>周六配送</li>
            </ul>
            {
                vegetable?.map(item=>{
                    return (
                        // <ShoppingItem {...item} flag={flag} NotAllSelected={NotAllSelected} key={item._id}/>
                        <SwipeAction
                            key={item._id}

                            //
                            rightActions={[
                                {
                                    /*NOTE:
                                        这里的 key 只是 rightActions 中内容的识别 不牵扯到真实内容
                                    */
                                    key: 'delete',
                                    text: '删除',
                                    color: 'danger',
                                    onClick: ()=>{
                                         Dialog.confirm({
                                            content:`确定要删除${item.name}吗`,
                                             //点击确认按钮后执行的操作
                                            onConfirm:async ()=>{
                                                try{
                                                    const result = await axios.get(`/api/delshoppingcart/${item._id}`)
                                                    console.log(result)
                                                    const message = result.data as Imessage
                                                    if(message.acknowledged){
                                                        Toast.show({
                                                            icon:'success',
                                                            content:'删除成功',
                                                            position:'center'
                                                        })
                                                        const newVegetable = vegetable?.filter(value=>value !== item)
                                                        setVegetable(newVegetable)
                                                        PubSub.publish('cartLength',message.shoppingCartLength)
                                                    }else {
                                                        throw new Error('删除出错')
                                                    }
                                                }catch (error){
                                                    Toast.show({
                                                        icon:'success',
                                                        content:'删除失败',
                                                        position:'center'
                                                    })
                                                }

                                            }
                                        })
                                    }
                                },
                            ]}
                        >
                            <ShoppingItem {...item} flag={flag} NotAllSelected={NotAllSelected}/>
                        </SwipeAction>
                    )
                })
            }
        </div>
    )
}